
from Memory.Celda import Celda
import time

class Memoria(object):

    def __init__(self, length):
        self.list = []
        self.length = length
        i = 0
        while(i < self.length):
            self.list.append(Celda(i))
            i = i + 1
    
    #Carga un programa en memoria      
    def load(self, aProgram, beginProgram):
        print("Se esta cargando en memoria el programa")
        print(aProgram)
        #time.sleep(1)
        i = beginProgram
        j = 0
        while j < len(aProgram.getInstructionList()):
            self.list.__getitem__(i).allokInstruction(aProgram.getInstructionList().__getitem__(j))
            print("Cargando instruccion: ")
            print(j)
            time.sleep(1)
            j = j + 1
            i = i + 1
        
    #Saca un programa de memoria  
    def unLoad(self, aProgram, beginProgram):
        i = beginProgram
        j = 0
        while j < len(aProgram.getInstructionList()):
            self.list.__getitem__(i).deallocate()
            j = j + 1
            i = i + 1
            
    #Carga una instruccion en memoria        
    def loadInstruction(self, anInstruction):
        positionFirstEmptyCell = self.list[self.positionFirstEmptyCell()] 
        positionFirstEmptyCell.instruction = anInstruction
        return positionFirstEmptyCell.position
        
    #Lee una instruccion de memoria               
    def read(self, instruction):
        return self.list[instruction]
        
    def getList(self):
        return self.list
    
    def setList(self, aList):
        self.list = aList
        
    def getLength(self):
        return self.length
    
    #Retorna true si no hay mas lugar en la memoria
    def isFull(self):
        j = 0
        for celda in self.list:
            if (not(celda.instruction == None)):
                j = j + 1
        
        return self.getLength() == j
    
    #Retorna la posicion de la primer celda vacia
    def positionFirstEmptyCell(self):
        for cell in self.list:
            if cell.instruction == None:
                return cell.position
   
    
    #Retorna la cantidad de celdas vacias        
    def countEmptyCells(self):
        i = 0
        for cell in self.list:
            if(cell.instruction == None):
                i = i + 1
        return i
    
    #Retororna la cantidad de celdas cargadas con una instruccion
    def countFullCells(self):
        return (self.length - self.countEmptyCells())
    
